import { query, queryAll } from '../utils/query';
import { getNextLevelData, searchData } from '../utils/data';
import { MenuManager } from '../managers/menu';
import { SelectionManager } from '../managers/selection';
import { ValueManager } from '../managers/value';
import type { CascaderOptions, CascaderOptionsData } from '../types/options';

/**
 * 事件处理器
 * 负责级联选择器的事件处理逻辑
 */
export class EventHandler {
    private uuid: string;
    private splitStr: string;
    private options: CascaderOptions;
    private menuManager: MenuManager;
    private selectionManager: SelectionManager;
    private valueManager: ValueManager;
    private valValue: any[];

    constructor(
        uuid: string,
        splitStr: string,
        options: CascaderOptions,
        menuManager: MenuManager,
        selectionManager: SelectionManager,
        valueManager: ValueManager,
        valValue: any[]
    ) {
        this.uuid = uuid;
        this.splitStr = splitStr;
        this.options = options;
        this.menuManager = menuManager;
        this.selectionManager = selectionManager;
        this.valueManager = valueManager;
        this.valValue = valValue;
    }

    /**
     * 初始化事件监听
     */
    public initEvents() {
        const { mode = "single", showSearch = false, searchDebounceTime = 300 } = this.options;

        const cascaderContainer = query(`.cascader-container_${this.uuid}`, this.uuid, true);

        // 点击组件以外区域，隐藏菜单并恢复值区域显示
        document.addEventListener("click", (e) => {
            const target = e.target as HTMLElement;
            if (!cascaderContainer?.contains(target) && !target.classList.contains(`cascader-container_value_placeholder`)) {
                this.menuManager.menusHide();
                // 如果启用了搜索功能，恢复值区域显示并隐藏搜索框
                if (this.options.showSearch) {
                    const valueElement = query(".cascader-container_value", this.uuid);
                    const editValueElement = query(".cascader-container_edit_value", this.uuid);
                    if (valueElement && editValueElement) {
                        valueElement.style.display = 'block';
                        editValueElement.style.display = 'none';
                    }
                }
            }
        });

        if (cascaderContainer) {
            cascaderContainer.onclick = (e) => {
                const target = e.target as HTMLElement;
                const targetClassList = target.classList;

                // 处理点击显示区域、值区域、占位符、已选项目、箭头等元素 - 显示下拉菜单
                if (
                    targetClassList.contains(`cascader-container_${this.uuid}`) ||
                    targetClassList.contains(`cascader-container_value_placeholder`) ||
                    targetClassList.contains(`cascader-container_value_item`) ||
                    targetClassList.contains(`cascader-container_arrow`) ||
                    targetClassList.contains(`cascader-container_arrow_icon`)
                ) {
                    this.menuManager.menusShow();
                    // 如果启用了搜索功能，显示搜索框并隐藏值区域
                    if (this.options.showSearch) {
                        const valueElement = query(".cascader-container_value", this.uuid);
                        const editValueElement = query(".cascader-container_edit_value", this.uuid);
                        if (valueElement && editValueElement) {
                            valueElement.style.display = 'none';
                            editValueElement.style.display = 'block';
                            // 聚焦到搜索框
                            const searchInput = query(".cascader-container_search_input", this.uuid) as HTMLInputElement;
                            if (searchInput) {
                                searchInput.focus();
                            }
                        }
                    }
                }
                // 处理点击清除按钮 - 清空选择值
                else if (target.closest(".cascader-container_clear")) {
                    this.setValue([]);
                }
                // 处理点击搜索结果项
                else if (target.closest(".cascader-container_menus_search_result_item:not(.cascader-container_menus_search_result_item_disabled)")) {
                    const resultItem = target.closest(".cascader-container_menus_search_result_item") as HTMLElement;
                    this.handleSearchResultSelect(resultItem);
                }
                // 处理点击搜索框清空按钮
                else if (target.closest(".cascader-container_search_clear")) {
                    e.stopPropagation();
                    this.menuManager.clearSearchBox();
                    // 清空搜索后，显示原始菜单
                    this.menuManager.resetMenu();
                }
                // 处理点击菜单项
                else {
                    // 获取当前点击的非禁用菜单项
                    const currentItem = target.closest(".cascader-container_menus_menu_item:not(.cascader-container_menus_menu_item_disabled)") as HTMLElement;

                    if (currentItem) {
                        // 获取当前菜单项的值标识
                        const currentItemTag = currentItem.dataset.value ?? "";
                        // 将值标识按分隔符拆分，得到当前完整的层级值数组
                        const currentValue = currentItemTag.split(this.splitStr);
                        // 获取当前值对应的下一级数据
                        const nextLevelData = getNextLevelData(currentValue, this.options);

                        // 检查是否点击的是多选模式下的父节点
                        const currentMultipleItem = target.closest(
                            ".cascader-container_menus_menu_item_multiple:not(.cascader-container_menus_menu_item_multiple_disabled)"
                        ) as HTMLElement;

                        // 处理多选模式下的父节点选择逻辑
                        if (currentMultipleItem && nextLevelData.length !== 0) {
                            // 过滤掉当前节点下已选择的值
                            this.valValue = [...this.valValue.filter((ele) => ele.join(this.splitStr).indexOf(currentItemTag) === -1)];

                            // 如果当前节点不是全选状态，则递归选择所有子节点
                            if (!currentItem.classList.contains("cascader-container_menus_menu_item_full")) {
                                // 递归函数：获取指定节点及其所有子节点的值路径
                                const recursion = (data: CascaderOptionsData, values: string[]) => {
                                    const { value, children } = data ?? {};

                                    // 如果有子节点，递归处理每个子节点
                                    if (children) {
                                        const arr: string[][] = [];

                                        for (let index = 0; index < children.length; index++) {
                                            arr.push(...recursion(children[index], [...values, String(value)]));
                                        }

                                        return arr;
                                    }

                                    // 如果是叶子节点，返回当前完整路径
                                    return [[...values, String(value)]];
                                };

                                const valueArr: any[] = [];

                                // 处理下一级所有节点，获取它们的完整路径
                                for (let index = 0; index < nextLevelData.length; index++) {
                                    const element = nextLevelData[index];
                                    valueArr.push(...recursion(element, currentValue));
                                }

                                // 将所有子节点的值路径添加到已选择值中
                                this.valValue = [...this.valValue, ...valueArr];
                            }
                        }
                        // 处理单选模式或叶子节点选择逻辑
                        else {
                            // 通过选择管理器更新菜单项的选中状态
                            this.selectionManager.selectItem(currentItem);

                            // 判断当前节点是否为叶子节点（没有下一级数据）
                            if (nextLevelData.length === 0) {
                                // 多选模式下的叶子节点选择逻辑
                                if (mode === "multiple") {
                                    // 检查当前值是否已存在于已选择值中
                                    if (this.valValue.map((ele) => ele.join(this.splitStr)).indexOf(currentValue.join(this.splitStr)) !== -1) {
                                        // 如果已存在，则移除（取消选择）
                                        const index = this.valValue.map((ele) => ele.join(this.splitStr)).findIndex((ele) => ele === currentValue.join(this.splitStr));
                                        this.valValue.splice(index, 1);
                                    } else {
                                        // 如果不存在，则添加（选择）
                                        this.valValue.push(currentValue);
                                    }
                                }
                                // 单选模式下的叶子节点选择逻辑
                                else {
                                    // 直接设置当前值为选中值
                                    this.valValue = [...currentValue];
                                    // 选择完成后隐藏菜单
                                    this.menuManager.menusHide();
                                }
                            }
                            // 处理非叶子节点选择逻辑
                            else {
                                // 获取当前节点的层级
                                const currentItemLevel = parseInt(currentItem.dataset.parentLevel ?? "0");
                                // 创建并显示下一级菜单
                                this.menuManager.createMenu(nextLevelData, currentItemLevel + 1, currentItemTag);
                            }
                        }

                        // 更新值的显示
                        this.valueManager.renderValue(this.valValue);
                        // 触发值变化回调，传递当前值、标签值和索引值
                        this.options.onChange?.(this.valValue, this.valueManager.transformValue("getLabelValue", this.valValue), this.valueManager.transformValue("getIndexValue", this.valValue));
                    }
                }
            };
        }

        // 如果启用了搜索功能，添加搜索相关事件
        if (showSearch) {
            // 防抖函数
            let searchTimer: number | null = null;
            
            // 直接获取搜索框元素并添加事件监听
            const searchInput = query(".cascader-container_search_input", this.uuid) as HTMLInputElement;
            
            if (searchInput) {
                // 阻止事件冒泡，避免触发菜单关闭
                searchInput.addEventListener("click", (e) => e.stopPropagation());
                
                // 搜索输入事件处理 - 使用防抖策略过滤菜单数据
                searchInput.addEventListener("input", (e) => {
                    // 清除之前的定时器以重置防抖
                    if (searchTimer !== null) {
                        clearTimeout(searchTimer);
                    }
                    
                    // 设置新的定时器，实现防抖延迟执行搜索
                    searchTimer = window.setTimeout(() => {
                        // 确保在防抖延迟后仍然可以正确访问到当前的this上下文
                        this.handleSearchInput(e);
                    }, searchDebounceTime);
                });
            }
        }
    }

    /**
     * 更新值
     * @param value 新的值
     */
    private setValue(value: any[]) {
        // 这里需要调用外部的setValue方法
        // 在实际使用中，可能需要通过回调或其他方式更新外部值
        this.valValue = value;
        this.valueManager.renderValue(this.valValue);
        this.options.onChange?.(this.valValue, this.valueManager.transformValue("getLabelValue", this.valValue), this.valueManager.transformValue("getIndexValue", this.valValue));
    }

    /**
     * 处理搜索输入事件
     * @param event 输入事件对象
     */
    private handleSearchInput(event: Event) {
        const target = event.target as HTMLInputElement;
        const keyword = target.value.trim();
        const clearBtn = query(".cascader-container_search_clear", this.uuid);

        // 显示/隐藏清空按钮
        if (clearBtn) {
            clearBtn.style.display = keyword ? 'flex' : 'none';
        }

        // 如果关键词为空，显示原始菜单
        if (!keyword) {
            this.menuManager.resetMenu();
            return;
        }

        // 执行搜索
        const { data, searchFn } = this.options;
        const results = searchData(data, keyword, searchFn);

        // 显示搜索结果
        this.menuManager.showSearchResults(results, keyword);
    }

    /**
     * 处理搜索结果选择事件
     * @param resultItem 搜索结果项元素
     */
    private handleSearchResultSelect(resultItem: HTMLElement) {
        const { mode = "single" } = this.options;
        const value = resultItem.dataset.value ?? "";
        const pathStr = resultItem.dataset.path ?? "";
        const path = pathStr.split(this.splitStr);

        // 在多选模式下，检查当前值是否已存在于已选择值中
        if (mode === "multiple") {
            const index = this.valValue.findIndex((ele: any[]) => ele.join(this.splitStr) === pathStr);
            
            if (index !== -1) {
                // 如果已存在，则移除（取消选择）
                this.valValue.splice(index, 1);
            } else {
                // 如果不存在，则添加（选择）
                this.valValue.push(path);
            }
        } else {
            // 单选模式下，直接设置当前值为选中值
            this.valValue = path;
            // 选择完成后隐藏菜单
            this.menuManager.menusHide();
        }

        // 更新值的显示
        this.valueManager.renderValue(this.valValue);
        // 触发值变化回调，传递当前值、标签值和索引值
        this.options.onChange?.(this.valValue, this.valueManager.transformValue("getLabelValue", this.valValue), this.valueManager.transformValue("getIndexValue", this.valValue));
    }
}